//
//  NewDIYViewModel.m
//  BigJoy
//
//  Created by Rowling on 2017/6/30.
//  Copyright © 2017年 Rowling. All rights reserved.
//

#import "NewDIYViewModel.h"
#import "DIYHomeCell.h"
@interface NewDIYViewModel()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    NSInteger _currentIndex;
    CGFloat _dragStartX;
    CGFloat _dragEndX;
}
@property (nonatomic,strong) UICollectionView * collectionView;
@property (nonatomic,weak)   UIView           * bindView;
@property (nonatomic,strong) NSMutableArray   * dataArray;
@property (nonatomic,strong) UIPageControl    * pageControl;
@end

@implementation NewDIYViewModel

-(UIPageControl *)pageControl {
    if (_pageControl == nil) {
        _pageControl = [[UIPageControl alloc]init];
        _pageControl.enabled = NO;
    }
    return _pageControl;
}

-(RACSubject *)subject {
    if (_subject == nil) {
        _subject = [[RACSubject alloc]init];
    }
    return _subject;
}

-(UICollectionView *)collectionView {
    if (_collectionView == nil) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(XMW(300),XMW(400));
        layout.minimumLineSpacing  = (0.2 * SCREEN_WIDTH ) / 4;
        layout.sectionInset = UIEdgeInsetsMake(0, 0.3 * SCREEN_WIDTH / 2, 10, 0.3 * SCREEN_WIDTH / 2);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, XMH(50), SCREEN_WIDTH, XMW(400) + 20) collectionViewLayout:layout];
        [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([DIYHomeCell class]) bundle:nil] forCellWithReuseIdentifier:@"Cell"];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}

#pragma mark CollectionDelegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    DIYHomeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.isList = NO;
    cell.imageView.image = [UIImage imageNamed:self.dataArray[indexPath.row]];
    return cell;
}

//配置cell居中
-(void)fixCellToCenter
{
    //最小滚动距离
    float dragMiniDistance = SCREEN_WIDTH/20.0f;
    if (_dragStartX -  _dragEndX >= dragMiniDistance) {
        _currentIndex -= 1;//向右
    }else if(_dragEndX -  _dragStartX >= dragMiniDistance){
        _currentIndex += 1;//向左
    }
    NSInteger maxIndex = [_collectionView numberOfItemsInSection:0] - 1;
    _currentIndex = _currentIndex <= 0 ? 0 : _currentIndex;
    _currentIndex = _currentIndex >= maxIndex ? maxIndex : _currentIndex;
    [self scrollToCenter];
    NSLog(@"%ld",_currentIndex);
}

//请求数据
-(void)loadData {
    self.dataArray = [NSMutableArray arrayWithArray:@[@"test1.jpg",@"jay.jpeg",@"1.jpeg",@"2.jpeg",@"test1.jpg",@"jay.jpeg",@"1.jpeg",@"2.jpeg"]];
    self.pageControl.numberOfPages = self.dataArray.count;
    [self makeCycle];
}
// pageControl
-(void)pageDotSetUI {
    for ( UIView * subView in self.pageControl.subviews) {
        subView.layer.borderWidth = 1;
        NSLog(@"%@",NSStringFromCGRect(subView.frame));
        subView.layer.borderColor = XMColor(152, 152, 152).CGColor;
    }
}

-(void)addpageConrol {
    [self.bindView addSubview:self.pageControl];
    self.pageControl.currentPageIndicatorTintColor = XMColor(152, 152, 152);
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).offset(XMW(10));
        make.centerX.equalTo(self.bindView);
    }];
//    [self.pageControl layoutIfNeeded];
//    [self.pageControl layoutSubviews];
//    [self.pageControl setNeedsDisplay];
//    [self pageDotSetUI];
//    [self.pageControl layoutIfNeeded];
//    [self.pageControl layoutSubviews];
//    [self.pageControl setNeedsDisplay];
//    [self pageDotSetUI];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self pageDotSetUI];
    });
}

-(void)setPgerControlPage:(NSInteger)currentindex {
    if (currentindex == 0) {
        self.pageControl.currentPage = self.dataArray.count - 2;
    }
    if (currentindex == 1) {
        self.pageControl.currentPage = self.dataArray.count - 1;
    }
    if (currentindex == self.dataArray.count - 2 ) {
        self.pageControl.currentPage = 0;
    }
    if (currentindex == self.dataArray.count - 1) {
        self.pageControl.currentPage = 1;
    }
    if (currentindex <= self.dataArray.count - 3 && currentindex >= 2) {
        self.pageControl.currentPage = currentindex - 2;
    }
}

-(void)setUI {
    [self.bindView addSubview:self.collectionView];
    [self fixCellToCenter];
    [self addpageConrol];
}

// 制造轮播数据
-(void)makeCycle {
    NSString * dic0 = [self.dataArray[0] copy];
    NSString * dic1 = [self.dataArray[1] copy];
    NSString * last0 = [[self.dataArray lastObject] copy];
    NSString * last1 = [self.dataArray[self.dataArray.count - 2] copy];
    [self.dataArray addObject:dic0];
    [self.dataArray  addObject:dic1];
    [self.dataArray insertObject:last0 atIndex:0];
    [self.dataArray insertObject:last1 atIndex:0];
    [self.collectionView reloadData];
    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    _currentIndex = 2;
}

// 绑定视图
-(void)bindViewModel:(UIView *)bindView {
    self.bindView = bindView;
    [self loadData];
    [self setUI];
}

-(void)scrollToCenter
{
    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    //    if (self.lunBo == NO) return;
    if (_currentIndex == 1 || _currentIndex == self.dataArray.count - 2 ) {
        self.collectionView.userInteractionEnabled = NO;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            usleep(300000);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (_currentIndex == 1) {
                    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count - 3 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
                    _currentIndex = self.dataArray.count - 3;
                }else if (_currentIndex == self.dataArray.count - 2) {
                    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
                    _currentIndex = 2;
                }
            });
            self.collectionView.userInteractionEnabled = YES;
        });
    }
    [self setPgerControlPage:_currentIndex];
}

//手指拖动开始
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _dragStartX = scrollView.contentOffset.x;
}

//手指拖动停止
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    _dragEndX = scrollView.contentOffset.x;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self fixCellToCenter];
    });
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.subject sendNext:@"push"];
}

@end
